package com.xja.wechat.common;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author CHENCHEN
 * @company XJA
 * @create 2019-11-20 15:46
 */
public class HttpClientUtil {

    public static String getRequest(String url, int timeOut) throws Exception {
        URL u = new URL(url);
        if ("https".equalsIgnoreCase(u.getProtocol())) {
            SslUtils.ignoreSsl();
        }
        URLConnection conn = u.openConnection();
        conn.setConnectTimeout(timeOut);
        conn.setReadTimeout(timeOut);
        return IOUtils.toString(conn.getInputStream());
    }

    public static String postRequest(String urlAddress, String args, int timeOut) throws Exception {
        URL url = new URL(urlAddress);
        if ("https".equalsIgnoreCase(url.getProtocol())) {
            SslUtils.ignoreSsl();
        }
        URLConnection u = url.openConnection();
        u.setDoInput(true);
        u.setDoOutput(true);
        u.setConnectTimeout(timeOut);
        u.setReadTimeout(timeOut);
        OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(), "UTF-8");
        osw.write(args);
        osw.flush();
        osw.close();
        u.getOutputStream();
        return IOUtils.toString(u.getInputStream());
    }

    public static JSONObject doGet(String url) throws IOException {
        JSONObject jsonObject = null;
        //发送请求为get请求，创建httpGet
        HttpGet httpGet = new HttpGet(url);
        //创建http请求连接
        HttpClient httpClient = new DefaultHttpClient();
        //执行发送请求，并得到响应结果
        HttpResponse httpResponse = httpClient.execute(httpGet);
        //判断请求是否成功
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            //获得响应结果
            String s = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            jsonObject = new JSONObject(s);
        }
        return jsonObject;
    }

    public static JSONObject doPost(String url, String str) throws IOException {
        JSONObject jsonObject = null;
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = new DefaultHttpClient();
        httpPost.setEntity(new StringEntity(str, "utf-8"));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            String s = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            jsonObject = new JSONObject(s);
        }
        return jsonObject;
    }
}
